home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pprint.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  10KB  |  317 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Support to pretty-print lists, tuples, & dictionaries recursively.
  5.  
  6. Very simple, but useful, especially in debugging data structures.
  7.  
  8. Classes
  9. -------
  10.  
  11. PrettyPrinter()
  12.     Handle pretty-printing operations onto a stream using a configured
  13.     set of formatting parameters.
  14.  
  15. Functions
  16. ---------
  17.  
  18. pformat()
  19.     Format a Python object into a pretty-printed representation.
  20.  
  21. pprint()
  22.     Pretty-print a Python object to a stream [default is sys.stdout].
  23.  
  24. saferepr()
  25.     Generate a 'standard' repr()-like value, but protect against recursive
  26.     data structures.
  27.  
  28. """
  29. import sys as _sys
  30. from cStringIO import StringIO as _StringIO
  31. __all__ = [
  32.     'pprint',
  33.     'pformat',
  34.     'isreadable',
  35.     'isrecursive',
  36.     'saferepr',
  37.     'PrettyPrinter']
  38. _commajoin = ', '.join
  39. _id = id
  40. _len = len
  41. _type = type
  42.  
  43. def pprint(object, stream = None, indent = 1, width = 80, depth = None):
  44.     '''Pretty-print a Python object to a stream [default is sys.stdout].'''
  45.     printer = PrettyPrinter(stream = stream, indent = indent, width = width, depth = depth)
  46.     printer.pprint(object)
  47.  
  48.  
  49. def pformat(object, indent = 1, width = 80, depth = None):
  50.     '''Format a Python object into a pretty-printed representation.'''
  51.     return PrettyPrinter(indent = indent, width = width, depth = depth).pformat(object)
  52.  
  53.  
  54. def saferepr(object):
  55.     '''Version of repr() which can handle recursive data structures.'''
  56.     return _safe_repr(object, { }, None, 0)[0]
  57.  
  58.  
  59. def isreadable(object):
  60.     '''Determine if saferepr(object) is readable by eval().'''
  61.     return _safe_repr(object, { }, None, 0)[1]
  62.  
  63.  
  64. def isrecursive(object):
  65.     '''Determine if object requires a recursive representation.'''
  66.     return _safe_repr(object, { }, None, 0)[2]
  67.  
  68.  
  69. class PrettyPrinter:
  70.     
  71.     def __init__(self, indent = 1, width = 80, depth = None, stream = None):
  72.         '''Handle pretty printing operations onto a stream using a set of
  73.         configured parameters.
  74.  
  75.         indent
  76.             Number of spaces to indent for each level of nesting.
  77.  
  78.         width
  79.             Attempted maximum number of columns in the output.
  80.  
  81.         depth
  82.             The maximum depth to print out nested structures.
  83.  
  84.         stream
  85.             The desired output stream.  If omitted (or false), the standard
  86.             output stream available at construction will be used.
  87.  
  88.         '''
  89.         indent = int(indent)
  90.         width = int(width)
  91.         if not indent >= 0:
  92.             raise AssertionError, 'indent must be >= 0'
  93.         if not depth is None and depth > 0:
  94.             raise AssertionError, 'depth must be > 0'
  95.         if not width:
  96.             raise AssertionError, 'width must be != 0'
  97.         self._depth = depth
  98.         self._indent_per_level = indent
  99.         self._width = width
  100.  
  101.     
  102.     def pprint(self, object):
  103.         self._format(object, self._stream, 0, 0, { }, 0)
  104.         self._stream.write('\n')
  105.  
  106.     
  107.     def pformat(self, object):
  108.         sio = _StringIO()
  109.         self._format(object, sio, 0, 0, { }, 0)
  110.         return sio.getvalue()
  111.  
  112.     
  113.     def isrecursive(self, object):
  114.         return self.format(object, { }, 0, 0)[2]
  115.  
  116.     
  117.     def isreadable(self, object):
  118.         (s, readable, recursive) = self.format(object, { }, 0, 0)
  119.         if readable:
  120.             pass
  121.         return not recursive
  122.  
  123.     
  124.     def _format(self, object, stream, indent, allowance, context, level):
  125.         level = level + 1
  126.         objid = _id(object)
  127.         if objid in context:
  128.             stream.write(_recursion(object))
  129.             self._recursive = True
  130.             self._readable = False
  131.             return None
  132.         rep = self._repr(object, context, level - 1)
  133.         typ = _type(object)
  134.         sepLines = _len(rep) > self._width - 1 - indent - allowance
  135.         write = stream.write
  136.         if self._depth and level > self._depth:
  137.             write(rep)
  138.             return None
  139.         r = getattr(typ, '__repr__', None)
  140.         if issubclass(typ, dict) and r is dict.__repr__:
  141.             write('{')
  142.             length = _len(object)
  143.             write('}')
  144.             return None
  145.         if not issubclass(typ, list) or r is list.__repr__:
  146.             if not issubclass(typ, tuple) or r is tuple.__repr__:
  147.                 if (issubclass(typ, set) or r is set.__repr__ or issubclass(typ, frozenset)) and r is frozenset.__repr__:
  148.                     length = _len(object)
  149.                     if issubclass(typ, list):
  150.                         write('[')
  151.                         endchar = ']'
  152.                     elif issubclass(typ, set):
  153.                         if not length:
  154.                             write('set()')
  155.                             return None
  156.                         write('set([')
  157.                         endchar = '])'
  158.                         object = sorted(object)
  159.                         indent += 4
  160.                     elif issubclass(typ, frozenset):
  161.                         if not length:
  162.                             write('frozenset()')
  163.                             return None
  164.                         write('frozenset([')
  165.                         endchar = '])'
  166.                         object = sorted(object)
  167.                         indent += 10
  168.                     else:
  169.                         write('(')
  170.                         endchar = ')'
  171.                     if issubclass(typ, tuple) and length == 1:
  172.                         write(',')
  173.                     
  174.                     write(endchar)
  175.                     return None
  176.                 write(rep)
  177.                 return None
  178.  
  179.     
  180.     def _repr(self, object, context, level):
  181.         (repr, readable, recursive) = self.format(object, context.copy(), self._depth, level)
  182.         if not readable:
  183.             self._readable = False
  184.         
  185.         if recursive:
  186.             self._recursive = True
  187.         
  188.         return repr
  189.  
  190.     
  191.     def format(self, object, context, maxlevels, level):
  192.         """Format object for a specific context, returning a string
  193.         and flags indicating whether the representation is 'readable'
  194.         and whether the object represents a recursive construct.
  195.         """
  196.         return _safe_repr(object, context, maxlevels, level)
  197.  
  198.  
  199.  
  200. def _safe_repr(object, context, maxlevels, level):
  201.     typ = _type(object)
  202.     if typ is str:
  203.         if 'locale' not in _sys.modules:
  204.             return (repr(object), True, False)
  205.         if "'" in object and '"' not in object:
  206.             closure = '"'
  207.             quotes = {
  208.                 '"': '\\"' }
  209.         else:
  210.             closure = "'"
  211.             quotes = {
  212.                 "'": "\\'" }
  213.         qget = quotes.get
  214.         sio = _StringIO()
  215.         write = sio.write
  216.         for char in object:
  217.             if char.isalpha():
  218.                 write(char)
  219.                 continue
  220.             write(qget(char, repr(char)[1:-1]))
  221.         
  222.         return ('%s%s%s' % (closure, sio.getvalue(), closure), True, False)
  223.     r = getattr(typ, '__repr__', None)
  224.     if issubclass(typ, dict) and r is dict.__repr__:
  225.         if not object:
  226.             return ('{}', True, False)
  227.         objid = _id(object)
  228.         if maxlevels and level >= maxlevels:
  229.             return ('{...}', False, objid in context)
  230.         if objid in context:
  231.             return (_recursion(object), False, True)
  232.         context[objid] = 1
  233.         readable = True
  234.         recursive = False
  235.         components = []
  236.         append = components.append
  237.         level += 1
  238.         saferepr = _safe_repr
  239.         for k, v in sorted(object.items()):
  240.             (krepr, kreadable, krecur) = saferepr(k, context, maxlevels, level)
  241.             (vrepr, vreadable, vrecur) = saferepr(v, context, maxlevels, level)
  242.             append('%s: %s' % (krepr, vrepr))
  243.             if readable and kreadable:
  244.                 pass
  245.             readable = vreadable
  246.             if krecur or vrecur:
  247.                 recursive = True
  248.                 continue
  249.             objid in context
  250.         
  251.         del context[objid]
  252.         return ('{%s}' % _commajoin(components), readable, recursive)
  253.     if (issubclass(typ, list) or r is list.__repr__ or issubclass(typ, tuple)) and r is tuple.__repr__:
  254.         if issubclass(typ, list):
  255.             if not object:
  256.                 return ('[]', True, False)
  257.             format = '[%s]'
  258.         elif _len(object) == 1:
  259.             format = '(%s,)'
  260.         elif not object:
  261.             return ('()', True, False)
  262.         typ is str
  263.         format = '(%s)'
  264.         objid = _id(object)
  265.         if maxlevels and level >= maxlevels:
  266.             return (format % '...', False, objid in context)
  267.         if objid in context:
  268.             return (_recursion(object), False, True)
  269.         context[objid] = 1
  270.         readable = True
  271.         recursive = False
  272.         components = []
  273.         append = components.append
  274.         level += 1
  275.         for o in object:
  276.             (orepr, oreadable, orecur) = _safe_repr(o, context, maxlevels, level)
  277.             append(orepr)
  278.             if orecur:
  279.                 recursive = True
  280.                 continue
  281.             None if not oreadable else level >= maxlevels
  282.         
  283.         del context[objid]
  284.         return (format % _commajoin(components), readable, recursive)
  285.     rep = repr(object)
  286.     if rep:
  287.         pass
  288.     return (rep, not rep.startswith('<'), False)
  289.  
  290.  
  291. def _recursion(object):
  292.     return '<Recursion on %s with id=%s>' % (_type(object).__name__, _id(object))
  293.  
  294.  
  295. def _perfcheck(object = None):
  296.     import time as time
  297.     if object is None:
  298.         object = [
  299.             ('string', (1, 2), [
  300.                 3,
  301.                 4], {
  302.                 5: 6,
  303.                 7: 8 })] * 100000
  304.     
  305.     p = PrettyPrinter()
  306.     t1 = time.time()
  307.     _safe_repr(object, { }, None, 0)
  308.     t2 = time.time()
  309.     p.pformat(object)
  310.     t3 = time.time()
  311.     print '_safe_repr:', t2 - t1
  312.     print 'pformat:', t3 - t2
  313.  
  314. if __name__ == '__main__':
  315.     _perfcheck()
  316.  
  317.